package com.coderdream.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.coderdream.dao.LoggingDao;
import com.coderdream.service.CoreService;
import com.coderdream.util.SignUtil;

/**
 * 请求处理的核心类
 * 
 */
public class CoreServlet extends HttpServlet {

	private static final long serialVersionUID = 7249839444661715592L;

	public static String TAG = "CoreServlet";

	private Logger logger = Logger.getLogger(CoreServlet.class);

	private LoggingDao loggingDao = new LoggingDao(this.getClass().getName());

	/**
	 * 请求校验（确认请求来自微信服务器）
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug(TAG + " ###### log4j debug doGet"
				+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		logger.debug(TAG + " ###### log4j debug doGet signature: " + signature + ", timestamp" + timestamp + ", nonce"
				+ nonce + ", echostr" + echostr);

		loggingDao.debug(TAG + " ###### log4j debug doGet signature: " + signature + ", timestamp" + timestamp + ", nonce"
				+ nonce + ", echostr" + echostr);

		PrintWriter out = response.getWriter();
		// 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 请求校验与处理
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug(TAG + " ######1 log4j debug doPost"
				+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
		// loggingDao.debug(TAG + " ######1 log4j debug doPost"
		// + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
		// String datetime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String signature = request.getParameter("signature");// 微信加密签名
		String timestamp = request.getParameter("timestamp");// 时间戳
		String nonce = request.getParameter("nonce");// 随机数
		String echostr = request.getParameter("echostr");// 随机字符串
		logger.debug(TAG + " ######2 log4j debug doPost signature: " + signature + ", timestamp" + timestamp + ", nonce"
				+ nonce + ", echostr" + echostr);
		loggingDao.debug(TAG + " ######2 log4j debug doPost signature: " + signature + ", timestamp" + timestamp
				+ ", nonce" + nonce + ", echostr" + echostr);
		PrintWriter out = response.getWriter();
		// 请求校验
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			// 从request中取得输入流
			InputStream inputStream = request.getInputStream();
			CoreService coreService = new CoreService();
			// 调用核心服务类接收处理请求
			String respXml = coreService.processRequest(inputStream);
			logger.debug(TAG + " ######4 log4j debug doPost respXml: " + respXml);
			loggingDao.debug(TAG + " ######4 log4j debug doPost respXml: " + respXml);
			out.print(respXml);
		}
		out.close();
		out = null;
	}
}